//
//  HomeHeaderView.m
//  YZMicroStock
//
//  Created by 王慕铁 on 2017/12/11.
//  Copyright © 2017年 cqjr. All rights reserved.
//

#import "HomeHeaderView.h"
#import "UIView+SubView.h"
#import "YZClient.h"
#import "YZGeneralResultModel.h"
#import "YZMHomeBannerModel.h"
#import "YZGeneralResultModel.h"
#import "YZMyStocksTopCell.h"
#import "HomeCenterView.h"
#import "YZMWebViewService.h"
#import <SDCycleScrollView.h>
#import <UIButton+WebCache.h>
#import "YZMAnnouncementModel.h"
#import "YZMAnnouncementListModel.h"
#import "YZMConfigureModel.h"
#import "YZClient+FreeExperience.h"
#import "NSNumber+Utils.h"

#define MARGIN 10


#define TOP_CELL_ROWHEIGHT   130


static NSString *const home_page_stock_cell_identifier = @"YZMyStocksTopCell";

@interface HomeHeaderView()<SDCycleScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic , strong) SDCycleScrollView* cycleScrollview;
@property (nonatomic , strong) UITableView*       tableView;
@property (nonatomic , strong) HomeCenterView*    center1;
@property (nonatomic , strong) HomeCenterView*    center2;
@property (nonatomic , strong) HomeCenterView*    center3;
@property (nonatomic , strong) HomeCenterView*    center4;

@end

@implementation HomeHeaderView {
    
    NSArray *_bannerArr;
    NSArray *_adArr;
    NSArray *_lastAdArr;
    NSMutableArray *_annArr;
    NSMutableArray *_imageUrlArr;
    NSMutableArray *_bannerData;
    
    NSMutableDictionary *_realDataDict;
    
    NSTimer *_stockTimer;
}

- (instancetype)init {
    
    if (self = [super init]) {
        
        [self initArray];
        
        [self createView];
        
        [self NetWork];
        
        
    }
    return self;
    
}

- (void)NetWork {
    [self fetchHomeBannerListWithErrorShowFlag];
    [self fetchStockDetailInfo];
    [self fetchFree];
}

- (void)initArray {
    _bannerData = [NSMutableArray array];
    _imageUrlArr = [NSMutableArray array];
    _realDataDict = [NSMutableDictionary dictionaryWithCapacity:1];
    _annArr = [NSMutableArray array];
}

- (void)createView {
    
    _cycleScrollview = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenWidth / 375 * 150) delegate:self placeholderImage:[UIImage imageNamed:@"loading"]];
    _cycleScrollview.backgroundColor = [YZMAppStyle colorForLightWhite];
    _cycleScrollview.autoScrollTimeInterval = 3.0;
    _cycleScrollview.pageControlAliment = SDCycleScrollViewPageContolAlimentCenterY;
    [self addSubview:_cycleScrollview];
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(MARGIN, _cycleScrollview.bottom - 35, ScreenWidth - 2 * MARGIN, TOP_CELL_ROWHEIGHT) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.scrollEnabled = NO;
    self.tableView.rowHeight = TOP_CELL_ROWHEIGHT;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.tableView registerClass:[YZMyStocksTopCell class] forCellReuseIdentifier:home_page_stock_cell_identifier];
    [self addSubview:self.tableView];
    
    CGFloat w = (ScreenWidth - 30) / 2;
    CGFloat h = w * (9.0/17.0);
    
    self.center1 = [[HomeCenterView alloc] initWithFrame:CGRectMake(MARGIN, self.tableView.bottom + MARGIN, w, h)];
    self.center2 = [[HomeCenterView alloc] initWithFrame:CGRectMake(self.center1.right + MARGIN, self.tableView.bottom + MARGIN, w, h)];
    self.center3 = [[HomeCenterView alloc] initWithFrame:CGRectMake(MARGIN, self.center1.bottom + MARGIN, w, h)];
    self.center4 = [[HomeCenterView alloc] initWithFrame:CGRectMake(self.center3.right + MARGIN, self.center3.top, w, h)];
 
    [self addSubviews:@[self.center1,self.center2,self.center3,self.center4]];
    
    [self.center1 setImage:@"免费体验" title:@"免费体验" detail:@"5000元操盘金免费领" imageT:nil];
    [self.center2 setImage:@"炒股大赛" title:@"炒股大赛" detail:@"万元奖金免费拿" imageT:nil];
    [self.center3 setImage:@"点买t+1" title:@"A股点买" detail:@"T+1/T+D供您选择" imageT:nil];
    [self.center4 setImage:@"点买t+d" title:@"盈利宝" detail:@"免服务费，短线利器" imageT:nil];
    
    [self.center1 addTarget:self action:@selector(webFirstButtonAction)];
    [self.center2 addTarget:self action:@selector(webSecondButtonAction)];
    [self.center3 addTarget:self action:@selector(firstButtonAction)];
    [self.center4 addTarget:self action:@selector(secondButtonAction)];
    
    self.frame = CGRectMake(0, 0, ScreenWidth, self.center4.bottom + 10);
}

- (void)startTimer{
    
    
    if (!_stockTimer) {
        
        _stockTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(fetchStockDetailInfo) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer: _stockTimer forMode: NSRunLoopCommonModes];
        [_stockTimer fire];
    }
}

- (void)stopTimer{
    
    if (_stockTimer) {
        
        if ([_stockTimer isValid]) {
            [_stockTimer invalidate];
        }
        _stockTimer = nil;
    }
    
}

- (void)fetchHomeBannerListWithErrorShowFlag {

    
    [YZClient fetchHomeBannerListWithSuccess:^(NSURLSessionDataTask *task, id responseObject) {
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"endRefreshing" object:nil];
            NSArray *bannerList = topModel.data;
            if (bannerList.count > 0) { //判断banner的个数是否大于0
                
                [_bannerData removeAllObjects];     //删除前次请求的banner内容
                [_bannerData addObjectsFromArray:bannerList];
                
                _bannerArr = [YZMHomeBannerModel mapResponseArray:_bannerData type:1];
                if (_bannerArr.count > 0) {
                    
                    //刷新banner数据
                    [self refreshBannerListView];
                }
                
                _adArr = [YZMHomeBannerModel mapResponseArray:_bannerData type:0];
                _lastAdArr = [YZMHomeBannerModel createDecoder];
                if (_adArr.count > 0 && ![_lastAdArr isEqualToArray:_adArr]) {
                    
                    //显示广告图
                    [self showAdView];
                }
            }
        }
 
    } failure:^(NSError *error) {
        
    }];
}

- (void)fetchStockDetailInfo{
    
    //    if ([self checkNetwork]) {
    //        _unFirstFetchAStockFlag=YES;
    //        return;
    //    }
    
    NSMutableArray *array = [NSMutableArray array];
    
    [array addObject:@"SH000001"];
    [array addObject:@"SZ399001"];
    [array addObject:@"SZ399006"];
    
    [YZClient qt_getRealtimeInfoWithStockCodes:array success:^(NSURLResponse *response, id responseObject) {
        

        YZGeneralResultModel *topModel = responseObject;
        if(topModel.success){
            [[NSNotificationCenter defaultCenter] postNotificationName:@"endRefreshing" object:nil];
            [_realDataDict removeAllObjects];
            [_realDataDict addEntriesFromDictionary:topModel.data];
//            if (_annArr.count > 0) {
//                [self.tableView reloadData];
//            } else {
                [self fetchAnnouncementList];
//            }
           
        }else{
            [topModel showMessage];
        }
    } failure:^(NSError *error) {
        
        if ([YZMHCMInstance.currentNavationCtroller.topViewController.class isSubclassOfClass:self.class]) {
            
            [error yz_showMessage];
        }

    }];
}

//请求公告列表
- (void)fetchAnnouncementList {
    
    [YZClient fetchNoticeListSuccess:^(NSURLSessionDataTask *task, id responseObject) {
        
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            YZMAnnouncementModel *model = topModel.data;
            if (model.items.count > 0) {
                
                [_annArr removeAllObjects];
                [_annArr addObjectsFromArray:model.items];
                
                [self.tableView reloadData];
            }
        }
    } failure:^(NSError *error) {
        
        
    }];
}

- (void)fetchFree {
    
    [YZClient freeEx_getConfigureDataSuccess:^(NSURLResponse *response, id responseObject) {
        YZGeneralResultModel *topModel=responseObject;
        if (topModel.success) {
            YZMFreeExperienceConfigureModel *model=topModel.data;
            
             [self.center1 setImage:@"免费体验" title:@"免费体验" detail:[@(model.totalMoney).p0fString stringByAppendingString:@"元操盘金免费领"] imageT:nil];
        }else{
//            if (failure) {
//                failure([NSError yz_errorWithBadResponse]);
//            }
        }
    } failure:^(NSError *error) {
//        if (failure) {
//            failure(error);
//        }
    }];

}

- (BOOL)checkNetwork {
    
    if (kNetworkNotReachability) {
        [MBProgressHUD showMessage:@"网络无法连接，请联网后重试"];
        return YES;
    }
    
    return NO;
}

- (void)refreshBannerListView {
    
    if (_bannerArr.count > 0) {
        
        [_imageUrlArr removeAllObjects];
        
        for (NSMutableDictionary *dic in _bannerArr) {
            
            //取得banner的下载地址List
            [_imageUrlArr addObject:dic[@"imageUrl"]];
        }

        if (_imageUrlArr.count > 0) {
            //轮播banner图
            _cycleScrollview.imageURLStringsGroup = _imageUrlArr;
            [[NSUserDefaults standardUserDefaults] setObject:_imageUrlArr forKey:@"bannerImageUrl"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
    }
}

- (void)showAdView {
    
    //取得keyWindow
    UIWindow *currentWindow = [UIApplication sharedApplication].keyWindow;
    //创建阴影按钮
    UIButton *shadowBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    shadowBtn.alpha = 0.6;
    shadowBtn.adjustsImageWhenHighlighted = NO;
    [shadowBtn setBackgroundImage:[UIImage createImageWithColor:[YZMAppStyle colorForBlackText]] forState:UIControlStateNormal];
    shadowBtn.tag = 120;
    [shadowBtn addTarget:self action:@selector(hideAdBtn) forControlEvents:UIControlEventTouchUpInside];
    [currentWindow addSubview:shadowBtn];
    [shadowBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(currentWindow);
    }];
    
    //创建广告弹窗
    UIButton *adBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    adBtn.backgroundColor = [UIColor clearColor];
    adBtn.tag = 130;
    adBtn.adjustsImageWhenHighlighted = NO;
    NSDictionary *dic = [_adArr lastObject];
    NSURL *url = [NSURL URLWithString:[dic[@"imageUrl"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];   //将下载地址转换为UTF8
//    [adBtn sd_setBackgroundImageWithURL:url forState:UIControlStateNormal placeholderImage:nil options:SDWebImageCacheMemoryOnly];
//    [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]
    [adBtn addTarget:self action:@selector(adToNextPage:) forControlEvents:UIControlEventTouchUpInside];
    [currentWindow addSubview:adBtn];
    [adBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.center.equalTo(shadowBtn);
        make.width.mas_equalTo(ceil(ScreenWidth * 0.7));
        make.height.mas_equalTo(ceil(ScreenWidth * 0.7 / 0.8));
    }];
    [adBtn sd_setBackgroundImageWithURL:url forState:UIControlStateNormal completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if (error) {
            [shadowBtn removeFromSuperview];
            [adBtn removeFromSuperview];
            UIButton *closeBtn = [currentWindow viewWithTag:140];
            if (closeBtn) {
                [closeBtn removeFromSuperview];
            }
            return ;
        }
        //将广告Data保存到本地，判断是否下次启动显示
        [YZMHomeBannerModel createEncoder:_adArr];
        CGSize size = image.size;
        [adBtn mas_updateConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(shadowBtn);
//            make.width.mas_equalTo(size.width);
//            make.height.mas_equalTo(size.height);
            make.width.mas_equalTo(ScreenWidth - 120);
            make.height.mas_equalTo((ScreenWidth - 120) *size.height / size.width);
        }];
    }];
    
    //关闭按钮
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    closeBtn.backgroundColor = [UIColor clearColor];
    closeBtn.tag = 140;
    closeBtn.adjustsImageWhenHighlighted = NO;
    [closeBtn addTarget:self action:@selector(hideAdBtn) forControlEvents:UIControlEventTouchUpInside];
    [currentWindow addSubview:closeBtn];
    [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.right.equalTo(adBtn);
        make.width.height.mas_equalTo(ceil(ScreenWidth * 0.7 * 0.2));
    }];
}

- (void)hideAdBtn {
    
    UIWindow *currentWindow = [UIApplication sharedApplication].keyWindow;
    UIButton *shadowBtn = [currentWindow viewWithTag:120];
    UIButton *adBtn = [currentWindow viewWithTag:130];
    UIButton *closeBtn = [currentWindow viewWithTag:140];
    //加动画效果
    [UIView animateWithDuration:0.3 animations:^{
        
        adBtn.alpha = 0;
    } completion:^(BOOL finished) {
        
        [adBtn removeFromSuperview];
        [closeBtn removeFromSuperview];
    }];
    
    [UIView animateWithDuration:0.5 animations:^{
        
        shadowBtn.alpha = 0;
    } completion:^(BOOL finished) {
        
        [shadowBtn removeFromSuperview];
    }];
}

- (void)adToNextPage:(UIButton *)send {
    
    [self hideAdBtn];
    [self bannerOrAdClick:[_adArr lastObject]];
}

- (void)bannerOrAdClick:(NSDictionary *)contentDic {
    
    NSDictionary *dic = contentDic[@"bannerEvent"];
    if ([dic[@"event"] isEqualToString:@""] && [dic[@"url"] isEqualToString:@""]) {
        
        return;
    }
    
    [YZMHomeBannerModel selectDirection:contentDic withLocal:YES];
}

- (void)webFirstButtonAction {
    BOOL isClicked =  [[NSUserDefaults standardUserDefaults] boolForKey:@"clikedFreeEx"];
    if (!isClicked) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"clikedFreeEx"];
    }
    [YZMWebViewService openFreeExperience];

}

- (void)webSecondButtonAction {
    [YZMWebViewService openSimulate];
}

-(void)firstButtonAction
{
    [YZMHCMInstance pushViewControllerWithName:@"stock" andParams:nil];
}

-(void)secondButtonAction
{
    [YZMHCMInstance pushViewControllerWithName:@"stockYLB" andParams:nil];
}

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    
    NSDictionary *dic = _bannerArr[index];
    [self bannerOrAdClick:dic];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YZMyStocksTopCell *cell = [tableView dequeueReusableCellWithIdentifier:home_page_stock_cell_identifier forIndexPath:indexPath];
    cell.layer.cornerRadius = MARGIN;
    cell.leftRecord = _realDataDict[@"SH000001"];
    cell.middleRecord = _realDataDict[@"SZ399001"];
    cell.rightRecord = _realDataDict[@"SZ399006"];
    if (_annArr.count > 0) {
        YZMAnnouncementListModel *model = _annArr[0];
        cell.adr = model.noticeTitle;
    }
 
    return cell;
}



@end 
